package com.yjs.app.trade.web.controller.business.statistics;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yjs.app.trade.core.util.DateUtil;
import com.yjs.app.trade.core.util.MongoUtil;
import com.yjs.app.trade.core.util.StringUtils;
import com.yjs.app.trade.entity.base.StatisticsConstant;
import com.yjs.app.trade.service.service.business.order.OrderService;
import com.yjs.app.trade.service.service.sys.UserService;
import com.yjs.app.trade.web.controller.base.BaseController;
import com.yjs.app.trade.web.controller.base.util.Result;

import net.sf.json.JSONObject;

/**
 * 发票相关控制层
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/app/business/statistics/dispatch")
public class DispatcherStatisticsController extends BaseController {

	@Autowired
	OrderService orderService;
	
	@Autowired
	UserService userService;
	
	/**
	 * 统计H5页面跳转
	 * @param type (areaList 地区, hospList 医院, compList 生产商)
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/statistics/index/{type}", method = RequestMethod.GET)
	public String statistics(@PathVariable String type, HttpServletRequest request) {
		String token = request.getHeader(userToken);
		if (StringUtils.isNotBlank(token)) {
			request.setAttribute("token", token);
			request.setAttribute("type", type);
			String ip = request.getLocalAddr();
			int port = request.getLocalPort();
			return "redirect:http://" + ip + ":" + port + "/yjs_app/resources/html/dist/index.html#/" + type + "?token=" + token + "&localUrl=" + "http://" + ip + ":" + port + "/yjs_app/";
		} else {
			return "error";
		}
	}
	
	public String getIp () {
		Enumeration<NetworkInterface> netInterfaces = null;
		try {
	        netInterfaces = NetworkInterface.getNetworkInterfaces();
	        while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                if (ni.getName().equals("eth3")) {
                	Enumeration<InetAddress> ips = ni.getInetAddresses();
                	while (ips.hasMoreElements()) {
                		return ips.nextElement().getHostAddress();
                	}
                }
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 配送30天每天订单信息
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dispatcherOrderPriceInfoThirtyDays", method = RequestMethod.GET)
	@ResponseBody
	public Object dispacherOrderPriceInfoThirtyDays(String data, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("dispatchId", getUserMemberId(request));
		List<String> projection = new ArrayList<String>();
		projection.add("dispatchId");
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		sorts.put("created", 1);
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId), passportId,StatisticsConstant.DispatchCollection.DISPATCHERORDERPRICEINFOTHIRTYDAYS);
		List<String> list = MongoUtil.getListInfo(changeCollectionName,map, projection, null, null, sorts);
		List<String> dates = DateUtil.getLastDates(new Date(), 30, Calendar.DATE, DateUtil.dateFormat);
		boolean flag = false;
		for (String string : dates) {
			flag = false;
			for (String json : list) {
				JSONObject jsonObject = JSONObject.fromObject(json);
				if (jsonObject.get("created") != null) {
					if (StringUtils.equals(string, jsonObject.getString("created"))) {
						flag = true;
					}
				}
			}
			if (!flag) {
				list.add("{\"created\":\"" + string + "\"}");
			}
		}
		list.sort(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				JSONObject jsonObject1 = JSONObject.fromObject(o1);
				JSONObject jsonObject2 = JSONObject.fromObject(o2);
				if (jsonObject1.get("created") != null && jsonObject2.get("created") != null ) {
					try {
						Date date1 = DateUtil.dateFormat.parse(jsonObject1.getString("created"));
						Date date2 = DateUtil.dateFormat.parse(jsonObject2.getString("created"));
						return DateUtil.compare_date(date1, date2);
					} catch (ParseException e) {
						e.printStackTrace();
						logger.error("买方日期排序出错:" + jsonObject1 + "&" + jsonObject2);
					}
				}
				return 0;
			}
		});
		return Result.csuccess(list);
	}
	/**
	 * 近12月配送金额
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dispatcherOrderTotalPriceTwelveMonths", method = RequestMethod.GET)
	@ResponseBody
	public Object dispatcherOrderTotalPriceTwelveMonths(String data, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("dispatchId", getUserMemberId(request));
		List<String> projection = new ArrayList<String>();
		projection.add("dispatchId");
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		sorts.put("years", 1);
		sorts.put("months", 1);
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,StatisticsConstant.DispatchCollection.DISPATCHERORDERTOTALPRICETWELVEMONTHS);
		List<String> list = MongoUtil.getListInfo(changeCollectionName, map, projection, null, null, sorts);
		List<String> dates = DateUtil.getLastDates(new Date(), 12, Calendar.MONTH, DateUtil.dateFormatMonth);
		String years = "";
		String months = "";
		boolean flag = false;
		for (String string : dates) {
			flag = false;
			for (String json : list) {
				JSONObject jsonObject = JSONObject.fromObject(json);
				if (jsonObject.get("years") != null && jsonObject.get("months") != null) {
					years = jsonObject.getString("years");
					months = jsonObject.getString("months");
					if (StringUtils.equals(string, years + "-" + months) ) {
						flag = true;
					}
				}
			}
			if (!flag) {
				String year = string.split("\\-")[0];
				String month = string.split("\\-")[1];
				list.add("{\"years\":\"" + year + "\", \"months\":\"" + month + "\", \"lastYears\":\"" + (Integer.parseInt(year) - 1) + "\", \"lastMonths\":\"" + month + "\"}");
			}
		}
		list.sort(new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				JSONObject jsonObject1 = JSONObject.fromObject(o1);
				JSONObject jsonObject2 = JSONObject.fromObject(o2);
				if (jsonObject1.get("years") != null && jsonObject2.get("years") != null &&
						jsonObject1.get("months") != null && jsonObject2.get("months") != null) {
					int year1 = jsonObject1.getInt("years");
					int year2 = jsonObject2.getInt("years");
					int month1 = jsonObject1.getInt("months");
					int month2 = jsonObject2.getInt("months");
					if (year1 > year2) {
						return 1;
					} else if (year1 == year2) {
						if (month1 > month2) {
							return 1;
						} else {
							return -1;
						}
					} else {
						return -1;
					}
				} else {
					return 0;
				}
			}
		});
		return Result.csuccess(list);
	}
	
	/**
	 * 年度总配送额
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dispatcherOrderTotalPriceYear", method = RequestMethod.GET)
	@ResponseBody
	public Object dispatcherOrderTotalPriceYear(String data, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		String passportId = getUserId(request);
		map.put("dispatchId", getUserMemberId(request));
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,StatisticsConstant.DispatchCollection.DISPATCHERORDERTOTALPRICEYEAR);
		return Result.csuccess(MongoUtil.composeNormalById(map, "dispatchId",changeCollectionName));
	}
	
	/**
	 * 查看今日订单信息
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/findDispatchTodayTotalOrderInfo", method = RequestMethod.GET)
	@ResponseBody
	public Object findDispatchTodayTotalOrder(String data, HttpServletRequest request) {
		String passportId = getUserId(request);
		if (userService.isManagerPassport(passportId)) {
			return Result.csuccess(orderService.findDispatchTodayTotalOrderInfo(getUserMemberId(request)));
		} else {
			return Result.csuccess(orderService.findDispatchPassportTodayTotalOrderInfo(getUserMemberId(request), passportId));
		}
	}
	
	/**
	 * 配送买方金额前十
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dispatcherOrderPriceBuyerTopTen", method = RequestMethod.GET)
	@ResponseBody
	public Object dispatcherOrderPriceBuyerTopTen(String data, HttpServletRequest request) {
		JSONObject jsonObject = dpackData(data);
		String type = jsonObject.getString("type");
		String mongoDbCollection = "";
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("dispatchId", getUserMemberId(request));
		if (StringUtils.strIsNotNull(jsonObject.get("dispatchId"))) {
			map.put("dispatchId", jsonObject.get("dispatchId"));
		} else {
			map.put("dispatchId", getUserMemberId(request));
		}
		map.put("type", type);
		if (StringUtils.strIsNotNull(jsonObject.get("productId")) ||
				StringUtils.strIsNotNull(jsonObject.get("productCode"))) {
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERORDERPRICEBUYERPRODUCTTOPTEN;
			if (StringUtils.strIsNotNull(jsonObject.get("productId"))) {
				map.put("productId", jsonObject.get("productId"));
			}
			if (StringUtils.strIsNotNull(jsonObject.get("productCode"))) {
				map.put("productCode", jsonObject.get("productCode"));
			}
		} else {
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERORDERPRICEBUYERTOPTEN;
		}
		List<String> projection = new ArrayList<String>();
		projection.add("dispatchId");
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		sorts.put("sort", 1);
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
		int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,mongoDbCollection);
		return Result.csuccess(MongoUtil.getListInfo(changeCollectionName, map, projection, pageNo, pageSize, sorts));
	}
	
	/**
	 * 配送金额前十
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/dispatcherOrderPriceProductTopTen", method = RequestMethod.GET)
	@ResponseBody
	public Object dispatcherOrderPriceProductTopTen(String data, HttpServletRequest request) {
		JSONObject jsonObject = dpackData(data);
		String type = jsonObject.getString("type");
		String mongoDbCollection = "";
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		
		map.put("dispatchId", getUserMemberId(request));
		map.put("type", type);
		if (jsonObject.get("regionId") != null) {
			map.put("region", jsonObject.getString("regionId"));
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERORDERPRICEPRODUCTREGIONTOPTEN;
		} else {
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERORDERPRICEPRODUCTTOPTEN;
		}
		List<String> projection = new ArrayList<String>();
		projection.add("dispatchId");
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		if (StringUtils.strIsNotNull(jsonObject.get("ranking"))) {
			sorts.put("ranking", jsonObject.getInt("ranking"));
		} else if (StringUtils.strIsNotNull(jsonObject.get("proportion"))) {
			sorts.put("orderNumber", jsonObject.getInt("proportion"));
		} else if (StringUtils.strIsNotNull(jsonObject.get("price"))) {
			sorts.put("orderNumber", jsonObject.getInt("price"));
		} else {
			sorts.put("sort", 1);
		}
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
		int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,mongoDbCollection);
		return Result.csuccess(MongoUtil.getListInfo(changeCollectionName, map, projection, pageNo, pageSize, sorts));
	}

	/**
	 * 配送方首页销售额 开票额 回款额
	 * @param data
	 * @param request
	 * @return
	 * @throws com.alibaba.dubbo.common.json.ParseException 
	 */
	@RequestMapping(value="/dispatcherOrderInvoicePriceByWeekMonthYear",method=RequestMethod.GET)
	@ResponseBody
	public Object dispatcherOrderInvoicePriceByWeekMonthYear(String data, HttpServletRequest request) throws com.alibaba.dubbo.common.json.ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		
		map.put("dispatchId", getUserMemberId(request));
		List<String> projection = new ArrayList<String>();
		projection.add("dispatchId");
		projection.add("created");
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,StatisticsConstant.DispatchCollection.DISPATCHERORDERINVOICEPRICEWEEKMONTHYEARDAYS);
		List<String> list = MongoUtil.getListInfo(changeCollectionName, map, projection, null, null, null);
		String[] str = new String[] {"WEEK","MONTH","YEAR"};
		boolean flag = false;
		if(list != null && list.size() != 0) {
			for (String string : str) {
				flag = false;
				for (String json : list) {
					JSONObject jsonObject = JSONObject.fromObject(json);
					if(jsonObject.containsValue(string)) {
						flag=true;
					}
				}			
				if(!flag) {
					list.add("{\"repaymentAmount\":\"0\",\"salesPrice\":\"0\",\"amountInvoice\":\"0\",\"dateType\":\""+string+"\"}");
				}
			}
		}else {
			for (String string : str) {
				list.add("{\"repaymentAmount\":\"0\",\"salesPrice\":\"0\",\"amountInvoice\":\"0\",\"dateType\":\""+string+"\"}");
			}
		}
		List<Map<String,Object>> listMap=new ArrayList<>();
		for (String st : list) {
			@SuppressWarnings("unchecked")
			HashMap<String, Object> maps = (HashMap<String, Object>) JSON.parseObject(st,HashMap.class);
			String price = (String) maps.get("repaymentAmount");
			double parseDoublea = Double.parseDouble(price);
			priceUtills(maps, parseDoublea,"repaymentAmount");
			
			String priceb = (String) maps.get("salesPrice");
			double parseDoubleb = Double.parseDouble(priceb);
			priceUtills(maps, parseDoubleb,"salesPrice");
			
			String pricec = (String) maps.get("amountInvoice");
			double parseDoublec = Double.parseDouble(pricec);
			priceUtills(maps, parseDoublec,"amountInvoice");
			
			listMap.add(maps);
		}
		return Result.csuccess(listMap);
	}

	private static void priceUtills(HashMap<String, Object> maps, double parseDouble,String keyName) {
		DecimalFormat de=new DecimalFormat("################0.00");
		if(parseDouble >= 10000 && parseDouble < 10000000){
			String format = de.format(parseDouble/10000);
			maps.put(keyName, format+"万");
		}else if(parseDouble >= 10000000 && parseDouble < 1000000000){
			String format = de.format(parseDouble/10000000);
			maps.put(keyName, format+"千万");
		}else if(parseDouble >= 1000000000){
			String format = de.format(parseDouble/1000000000);
			maps.put(keyName, format+"亿");
		}else{
			String format = de.format(parseDouble);
			maps.put(keyName, format+"元");
		}
	}
	
	public static void main(String[] args) {
		HashMap<String,Object> map=new HashMap<String,Object>();
		map.put("repaymentAmount","4333354456452.232");
		map.put("salesPrice","100");
		map.put("amountInvoice","12340000");
		String price = (String) map.get("repaymentAmount");
		double parseDouble = Double.parseDouble(price);
		String priceb = (String) map.get("salesPrice");
		double parseDoubleb = Double.parseDouble(priceb);
		String pricec = (String) map.get("amountInvoice");
		double parseDoublec = Double.parseDouble(pricec);
		priceUtills(map,parseDouble,"repaymentAmount");
		priceUtills(map,parseDoubleb,"salesPrice");
		priceUtills(map,parseDoublec,"amountInvoice");
		//System.out.println(map.toString());
	}
	
	
	/**
	 * 配送方首页诚信评价分数(废弃了)
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/dispatcherIntegrityEvaluationMonthYear",method=RequestMethod.GET)
	@ResponseBody
	public Object dispatcherIntegrityEvaluationMonthYear(String data,HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("MEMBER_ID", getUserMemberId(request));
		List<String> projection = new ArrayList<String>();
		projection.add("MEMBER_ID");
		projection.add("WD_CODE");
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,StatisticsConstant.DispatchCollection.DISPATCHERINTEGRITYEVALUATIONMONTHYEAR);
		List<String> list = MongoUtil.getListInfo(changeCollectionName, map, projection, null, null, null);
		String[] str = new String[] {"MONTH","YEAR"};
		boolean flag = false;
		if(list != null && list.size() != 0) {
			for (String string : str) {
				flag = false;
				for (String json : list) {
					JSONObject jsonObject = JSONObject.fromObject(json);
					if(jsonObject.containsValue(string)) {
						flag=true;
					}
				}			
				if(!flag) {
					list.add("{\"TOTAL_SCORE\":\"0\",\"DATE_TYPE\":\""+string+"\"}");
				}
			}
		}else {
			for (String string : str) {
				list.add("{\"TOTAL_SCORE\":\"0\",\"DATE_TYPE\":\""+string+"\"}");
			}
		}
		return Result.csuccess(list);
	}
	
	/**
	 * by jiey
	 * 区域 销售分析
	 * 医院销售分析
	 * 企业生产销售分析
	 */
	@RequestMapping(value = "/dispatcherOrderAnalysis")
	@ResponseBody
	public Object dispatcherOrderAnalysis(String data, HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		JSONObject jsonObject = dpackData(data);
//		logger.info("进入区域配送----------------");
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		//Pattern pattern = Pattern.compile("^.*上药康德乐.*$", Pattern.CASE_INSENSITIVE);
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("dispatchId", getUserMemberId(request));
		//当为time=1（近30天）当为time=2（近7天）
		if(StringUtils.strIsNotNull(jsonObject.get("time"))){
			map.put("time", jsonObject.getString("time"));
		}else{
			map.put("time",'2');
		}
		//sort =1 升序  sort =-1 降序
		if(StringUtils.strIsNotNull(jsonObject.getInt("sort"))){
			sorts.put("maketRatio", jsonObject.getInt("sort"));
		}else{
			sorts.put("maketRatio",1);
		}	
		String mongoDbCollection = "";
		String type = jsonObject.getString("type");
		//String type="DISPATCHERareainfo";
		if(type.equals("dispatcherareainfo")){
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERAREAINFO;
			if(StringUtils.strIsNotNull(jsonObject.get("param"))){
				map.put("regionName", jsonObject.getString("param"));
			}
		}else if(type.equals("dispatcherbuyerinfo")){
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERBUYERINFO;
			if(StringUtils.strIsNotNull(jsonObject.get("param"))){
				map.put("buyerName", Pattern.compile("^.*" +jsonObject.getString("param") +".*$", Pattern.CASE_INSENSITIVE));
			}
		}else {		
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERSELLERINFO;
			if(StringUtils.strIsNotNull(jsonObject.get("param"))){
				map.put("sellerName", Pattern.compile("^.*" +jsonObject.getString("param") +".*$", Pattern.CASE_INSENSITIVE));
			}
		}
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
		int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
		String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,mongoDbCollection);
		return Result.csuccess(MongoUtil.getListInfo(changeCollectionName, map, null, pageNo, pageSize, sorts));
	}
	/**
	 * by jiey
	 * 区域 销售药品分析
	 * 医院销售药品分析
	 * 企业生产销售药品分析
	 */
	@RequestMapping(value = "/dispatcherOrderAnalysisDrug")
	@ResponseBody
	public Object dispatcherOrderAnalysisDrug(String data, HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		JSONObject jsonObject = dpackData(data);
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("dates", jsonObject.get("dates"));
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		map.put("dispatchId", getUserMemberId(request));
		if(StringUtils.strIsNotNull(jsonObject.get("time"))){
			map.put("time", jsonObject.getString("time"));
		}else{
			map.put("time",'2');
		}
		//sort =1 升序  sort =-1 降序
		if(StringUtils.strIsNotNull(jsonObject.get("sort"))){
			sorts.put("maketRatio", jsonObject.getInt("sort"));
		}else{
			sorts.put("maketRatio",1);
		}
		String mongoDbCollection = "";
		if(StringUtils.strIsNotNull(jsonObject.get("productId"))){
			map.put("productId", Pattern.compile("^.*" +jsonObject.getString("productId") +".*$", Pattern.CASE_INSENSITIVE));
		}
		if(StringUtils.strIsNotNull(jsonObject.get("productName"))){
			map.put("productName", Pattern.compile("^.*" +jsonObject.getString("productName") +".*$", Pattern.CASE_INSENSITIVE));
		}
		String type = jsonObject.getString("type");
		 if(type.equals("dispatcherareadetail")){
			 map.put("regionName", jsonObject.getString("param"));			 
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERAREADETAIL;
		}else if(type.equals("dispatcherbuyerdetail")){
			map.put("buyerName", jsonObject.getString("param"));
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERBUYERDETAIL;
		}else if(type.equals("dispatchersellerdetail")){
			map.put("sellerName", jsonObject.getString("param"));
			mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHERSELLERDETAIL;
		}

		 int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
	     int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
	     String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
					passportId,mongoDbCollection);
	     
		return Result.csuccess(MongoUtil.getListInfo(changeCollectionName, map, null, pageNo, pageSize, sorts));
	}
	
	@RequestMapping(value = "/dispatchPassportSaleTotalPrice")
	@ResponseBody
	public Object dispatchPassportSaleTotalPrice(String data, HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = dpackData(data);
		//System.out.println(jsonObject);
		Map<String, Object> map = new HashMap<String, Object>();
		String passportId = getUserId(request);
		map.put("dates", jsonObject.get("dates"));
		if (StringUtils.strIsNotNull(jsonObject.get("username"))) {
			map.put("passportName", Pattern.compile("^.*" +jsonObject.getString("username") +".*$", Pattern.CASE_INSENSITIVE));
		}
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		map.put("memberId", getUserMemberId(request));
		if (StringUtils.strIsNotNull(jsonObject.get("passportName"))) {
			sorts.put("passportName",Integer.parseInt(jsonObject.get("passportName").toString()));
		} else if (StringUtils.strIsNotNull(jsonObject.get("invoicePrice"))) {
			sorts.put("invoicePrice", Integer.parseInt(jsonObject.get("invoicePrice").toString()));
		} else {
			sorts.put("invoicePrice", -1);
		}
		String mongoDbCollection = StatisticsConstant.DispatchCollection.DISPATCHPASSPORTSALETOTALPRICE;
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
	    int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
	    String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,mongoDbCollection);
		return Result.csuccess(MongoUtil.getListInfo(changeCollectionName, map, null, pageNo, pageSize, sorts));
	}
	
	@RequestMapping(value = "/dispatchPassportSaleProductTotalPrice")
	@ResponseBody
	public Object dispatchPassportSaleProductTotalPrice(String data, HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = dpackData(data);
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		map.put("passportId", jsonObject.getString("passportId"));
		map.put("dates", jsonObject.getString("dates"));
		if (StringUtils.strIsNotNull(jsonObject.get("productId"))) {
			map.put("productId", Pattern.compile("^.*" +jsonObject.getString("productId") +".*$", Pattern.CASE_INSENSITIVE));
		}
		if (StringUtils.strIsNotNull(jsonObject.get("productName"))) {
			map.put("productName", Pattern.compile("^.*" +jsonObject.getString("productName") +".*$", Pattern.CASE_INSENSITIVE));
		}
		String mongoDbCollection = jsonObject.getString("type");
		if (StringUtils.strIsNotNull(jsonObject.get("productSort"))) {
			sorts.put("productName",Integer.parseInt(jsonObject.get("productSort").toString()));
		} else if (StringUtils.strIsNotNull(jsonObject.get("orderTotalPrice"))) {
			sorts.put("orderTotalPrice", Integer.parseInt(jsonObject.get("orderTotalPrice").toString()));
		} else {
			sorts.put("orderTotalPrice", -1);
		}
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
	    int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
		return Result.csuccess(MongoUtil.getListInfo(mongoDbCollection, map, null, pageNo, pageSize, sorts));
	}
	
	/**
	 * 品规销售医院产品分析
	 * @author zjh 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 * @
	 */
	@RequestMapping(value = "/dispatchBuyerProduct")
	@ResponseBody
	public Object dispatchbuyerproduct(String data, HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = dpackData(data);
		String passportId = getUserId(request);
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		map.put("dispatchId", getUserMemberId(request));
		map.put("productCode", jsonObject.getString("productCode"));
		map.put("time", jsonObject.getString("time"));
		String mongoDbCollection =StatisticsConstant.DispatchCollection.DISPATCHBUYERPRODUCT;
		if (StringUtils.strIsNotNull(jsonObject.get("productSort"))) {
			sorts.put("productPrice", Integer.parseInt(jsonObject.get("productSort").toString()));
		}else{
			sorts.put("productPrice", -1);
		}
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
	    int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
	    String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,mongoDbCollection);
		return Result.csuccess(MongoUtil.getListInfo(changeCollectionName, map, null, pageNo, pageSize, sorts));
	}
	/**
	 * 品规销售区域产品分析
	 * @author zjh 
	 * @param data
	 * @param request
	 * @param response
	 * @return
	 * @
	 */
	@RequestMapping(value = "/dispatchRegionProduct")
	@ResponseBody
	public Object dispatchpassportregionproduct(String data, HttpServletRequest request, HttpServletResponse response) {
		JSONObject jsonObject = dpackData(data);
		String passportId = getUserId(request);
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Integer> sorts = new HashMap<String, Integer>();
		map.put("dispatchId", getUserMemberId(request));
		map.put("productCode", jsonObject.getString("productCode"));
		map.put("time", jsonObject.getString("time"));
		String mongoDbCollection =StatisticsConstant.DispatchCollection.DISPATCHREGIONPRODUCT;
		if (StringUtils.strIsNotNull(jsonObject.get("productSort"))) {
			sorts.put("productPrice", Integer.parseInt(jsonObject.get("productSort").toString()));
		}else{
			sorts.put("productPrice", -1);
		}
		int pageNo = jsonObject.get("pageNo") != null ? jsonObject.getInt("pageNo") : 1;
	    int pageSize = jsonObject.get("pageSize") != null ? jsonObject.getInt("pageSize") : 10;
	    String changeCollectionName = changeCollectionName(map, userService.isManagerPassport(passportId),
				passportId,mongoDbCollection);
	    //System.out.println(map.toString());
	    List<String> listInfo = MongoUtil.getListInfo(changeCollectionName, map, null, pageNo, pageSize, sorts);
	    //System.out.println(listInfo);
		return Result.csuccess(listInfo);
	}
}

